package com.cloud.example.business.transaction.depend;

import com.cloud.async.flow.web.client.FlowTemplate;
import com.cloud.async.flow.worker.WorkResult;
import com.cloud.async.flow.wrapper.WorkerWrapper;
import com.cloud.example.business.transaction.depend.worker.DeWorker;
import com.cloud.example.business.transaction.depend.worker.DeWorker1;
import com.cloud.example.business.transaction.depend.worker.DeWorker2;
import com.cloud.example.business.transaction.depend.worker.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * 后面请求依赖于前面请求的执行结果
 *
 * @author chengr
 */
@RequestMapping("/api/tx")
@RestController
public class TransactionController {

    /**
     * logger
     */
    private final Log logger = LogFactory.getLog(getClass());

    @Autowired
    DeWorker deWorker;

    @Autowired
    DeWorker1 deWorker1;

    @Autowired
    DeWorker2 deWorker2;


    @Autowired
    FlowTemplate flowTemplate;

    @GetMapping("/transaction")
    public String depend() throws ExecutionException {



        WorkerWrapper<WorkResult<User>, User> workerWrapper1 = new WorkerWrapper.Builder<WorkResult<User>, User>()
                .worker(deWorker1)
                .callback(deWorker1)
                .id("second")
                //.next(workerWrapper2)
                .build(true);

        WorkerWrapper<String, User> workerWrapper = new WorkerWrapper.Builder<String, User>()
                .worker(deWorker)
                .param("workerWrapper params")
                .id("first")
                .next(workerWrapper1, true)
                .callback(deWorker)
                .build(true);
        System.out.println(Thread.currentThread().getName());

        WorkResult<User> result = workerWrapper.getWorkResult();
        WorkResult<User> result1 = workerWrapper1.getWorkResult();
        workerWrapper1.setParam(result);


        //模拟异常
        WorkerWrapper<String, User> workerWrapper2 = new WorkerWrapper.Builder<String, User>()
                .worker(deWorker2)
                .callback(deWorker2)
                .param("test2")
                .id("third")
                .build(true);


        flowTemplate.startTransaction(99999999, workerWrapper, workerWrapper2);

        logger.info("------end------");
        logger.info("worker0 的结果是：" + workerWrapper.getWorkResult());
        logger.info("worker1 的结果是：" + workerWrapper1.getWorkResult());
        logger.info("worker2 的结果是：" + workerWrapper2.getWorkResult());

        return "success!";
    }


}
